import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useQuestionStore } from '@/stores/question'
import { executionApi } from '@/api/execution'
import { submissionApi } from '@/api/submission'
import { solutionApi } from '@/api/solution'
import { discussionApi } from '@/api/discussion'
import { questionApi } from '@/api/question'
import type { Question } from '@/types'

export function useQuestionDetail() {
  const route = useRoute()
  const router = useRouter()
  const questionStore = useQuestionStore()

  // 响应式数据
  const currentQuestion = ref<Question | null>(null)
  const questionLoading = ref(false)
  const questionError = ref('')
  const currentCode = ref('')
  const selectedLanguage = ref('python')
  const selectedTheme = ref('dracula')
  const isRunning = ref(false)
  const isSubmitting = ref(false)
  const runOutput = ref('')
  const runError = ref('')
  const customInput = ref('')
  const currentSubmission = ref<any>(null)
  const solutions = ref<any[]>([])
  const discussions = ref<any[]>([])
  const sidebarExpanded = ref(false)
  const isQuestionFullscreen = ref(false)
  const isCodeFullscreen = ref(false)
  const isCodeCompletionDisabled = ref(false)

  // 计算属性
  const questionId = computed(() => parseInt(route.params.id as string))

  // 方法
  const loadQuestion = async () => {
    if (!questionId.value) return

    try {
      questionLoading.value = true
      questionError.value = ''
      
      const response = await questionApi.getQuestion(questionId.value)
      if (response.data) {
        currentQuestion.value = response.data
        // 加载用户代码
        if (response.data.basecode && response.data.basecode[selectedLanguage.value]) {
          currentCode.value = response.data.basecode[selectedLanguage.value]
        }
      }
    } catch (error: any) {
      console.error('加载题目失败:', error)
      questionError.value = error.message || '加载题目失败'
    } finally {
      questionLoading.value = false
    }
  }

  const loadSolutions = async () => {
    if (!questionId.value) return

    try {
      const response = await solutionApi.getSolutions(questionId.value)
      if (response.data) {
        solutions.value = response.data.solutions || []
      }
    } catch (error) {
      console.error('加载题解失败:', error)
    }
  }

  const loadDiscussions = async () => {
    if (!questionId.value) return

    try {
      const response = await discussionApi.getDiscussions({ category: `question_${questionId.value}` })
      if (response.data) {
        discussions.value = response.data.discussions || []
      }
    } catch (error) {
      console.error('加载讨论失败:', error)
    }
  }

  const runCode = async () => {
    if (!currentCode.value.trim()) return

    try {
      isRunning.value = true
      runOutput.value = ''
      runError.value = ''

      const response = await executionApi.runCode({
        question_id: questionId.value!,
        code: currentCode.value,
        language: selectedLanguage.value,
        input: customInput.value
      })

      if (response.data) {
        runOutput.value = response.data.output || ''
        runError.value = response.data.error || ''
      }
    } catch (error: any) {
      console.error('运行代码失败:', error)
      runError.value = error.message || '运行失败'
    } finally {
      isRunning.value = false
    }
  }

  const submitCode = async () => {
    if (!currentCode.value.trim()) return

    try {
      isSubmitting.value = true

      const response = await executionApi.submitCode({
        question_id: questionId.value!,
        language: selectedLanguage.value,
        code: currentCode.value
      })

      if (response.data) {
        currentSubmission.value = response.data
        // 跳转到提交详情页
        router.push(`/submission/${response.data.id}`)
      }
    } catch (error: any) {
      console.error('提交代码失败:', error)
    } finally {
      isSubmitting.value = false
    }
  }

  const toggleFavorite = async () => {
    if (!currentQuestion.value) return

    try {
      if (currentQuestion.value.is_favorited) {
        await questionStore.unfavoriteQuestion(currentQuestion.value.id)
        currentQuestion.value.is_favorited = false
      } else {
        await questionStore.favoriteQuestion(currentQuestion.value.id)
        currentQuestion.value.is_favorited = true
      }
    } catch (error) {
      console.error('收藏操作失败:', error)
    }
  }

  const toggleSidebar = () => {
    sidebarExpanded.value = !sidebarExpanded.value
  }

  const toggleQuestionFullscreen = () => {
    isQuestionFullscreen.value = !isQuestionFullscreen.value
  }

  const toggleCodeFullscreen = () => {
    isCodeFullscreen.value = !isCodeFullscreen.value
  }

  const toggleCodeCompletion = () => {
    isCodeCompletionDisabled.value = !isCodeCompletionDisabled.value
  }

  // 监听路由变化
  watch(() => route.params.id, (newId) => {
    if (newId) {
      loadQuestion()
      loadSolutions()
      loadDiscussions()
    }
  })

  onMounted(() => {
    loadQuestion()
    loadSolutions()
    loadDiscussions()
  })

  return {
    // 状态
    currentQuestion,
    questionLoading,
    questionError,
    currentCode,
    selectedLanguage,
    selectedTheme,
    isRunning,
    isSubmitting,
    runOutput,
    runError,
    customInput,
    currentSubmission,
    solutions,
    discussions,
    sidebarExpanded,
    isQuestionFullscreen,
    isCodeFullscreen,
    isCodeCompletionDisabled,

    // 计算属性
    questionId,

    // 方法
    loadQuestion,
    loadSolutions,
    loadDiscussions,
    runCode,
    submitCode,
    toggleFavorite,
    toggleSidebar,
    toggleQuestionFullscreen,
    toggleCodeFullscreen,
    toggleCodeCompletion
  }
}

